//
//  QNUploadManger.m
//  catVoice
//
//  Created by apple on 2019/7/17.
//  Copyright © 2019 imac. All rights reserved.
//

#import "TMQNUploadManger.h"
#import <Qiniu-umbrella.h>
@implementation TMQNUploadManger
+ (TMQNUploadManger *)manger{
    static TMQNUploadManger * manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = TMQNUploadManger.new;
    });
    return manger;
}
- (NSString*)qntoken{
    return [STTools_UserManger defult].qnToken;
}
- (NSString*)qnhead{
    return [STTools_UserManger defult].qNhead;
}
#pragma mark --七牛
- (void)sendQiNiuWithImage:(UIImage *)image handle:(void (^)(NSString *))handle{
    NSData * data = UIImageJPEGRepresentation(image, 0.7);
    UIImage *  dealImage = [UIImage imageWithData:data];
    if (self.qntoken.length) {
        NSString * filePath = [self getImagePath:dealImage];
        [self sendFileWithFilePath:filePath handle:handle];
        
    }else{
        if (handle) {
            handle(nil);
        }
    }
}
- (void)sendQiNiuGifWithData:(NSData *)data handle:(void (^)(NSString *))handle{
    
    if (self.qntoken.length && data) {
        [self sendGifFileWithData:data handle:handle];
    }else{
        if (handle) {
            handle(nil);
        }
    }
}
- (void)sendFileWithFilePath:(NSString *)path handle:(void (^)(NSString *))handle{
    NSString *token = [self qntoken];
    QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
        builder.zone = [QNFixedZone zone2];
    }];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:@"" progressHandler:^(NSString *key, float percent) {
        // NSLog(@"percent == %.2f", percent);
    }
                                                                 params:nil
                                                               checkCrc:NO
                                                     cancellationSignal:nil];
    
    NSLog(@"文件filePath = %@",path);
    NSString * keyName;
    if (STTools_UserManger.defult.stoneobs_fun_get_loginedUser.uid) {
        keyName = [NSString stringWithFormat:@"%@%ld%ld.png",STTools_UserManger.defult.stoneobs_fun_get_loginedUser.uid,@(NSDate.date.timeIntervalSince1970).integerValue,arc4random()%100000000];
    }
    UIImage * image = [[UIImage alloc] initWithContentsOfFile:path];
    [upManager putFile:path key:keyName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        // NSLog(@"info ===== %@", info);
        NSLog(@"上传图片结果 resp===== %@  info = %@  \n  key = %@", resp,info,key);
        if ([resp.allKeys containsObject:@"key"]) {
            NSString * imageUrl = [NSString stringWithFormat:@"%@%@",self.qnhead,resp[@"key"]];
            if (handle) {
                handle(imageUrl);
            }
        }else{
            handle(nil);
        }
    }
                option:uploadOption];
}
- (void)sendFileWithFilePath:(NSString*)path type:(NSString*)type handle:(void(^)(NSString* url))handle{
    NSString *token = self.qntoken;
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:@"" progressHandler:^(NSString *key, float percent) {
        NSLog(@" path = %@,percent == %.2f",path, percent);
    }
                                                                 params:nil
                                                               checkCrc:NO
                                                     cancellationSignal:nil];
    
    NSLog(@"文件filePath = %@",path);
    NSString * dateSine1970 = [NSString stringWithFormat:@"%ld",@(NSDate.date.timeIntervalSince1970).integerValue];
    NSString * userId = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.uid;
    NSString * keyName = [NSString stringWithFormat:@"%@_%@_%@%@",userId,dateSine1970,@"0",type];
    [upManager putFile:path key:keyName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        // NSLog(@"info ===== %@", info);
        //NSLog(@"resp ===== %@", resp);
        if ([resp.allKeys containsObject:@"key"]) {
            NSString * imageUrl = [NSString stringWithFormat:@"%@%@",self.qnhead,resp[@"key"]];
            if (handle) {
                handle(imageUrl);
            }
        }
    }
                option:uploadOption];
}

- (void)sendGifFileWithData:(NSData*)data handle:(void (^)(NSString *))handle{
    NSString *token = self.qntoken;
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:@"image/gif" progressHandler:^(NSString *key, float percent) {
        // NSLog(@"percent == %.2f", percent);
    }
                                                                 params:nil
                                                               checkCrc:NO
                                                     cancellationSignal:nil];
    
    
    NSString * keyName = [NSString stringWithFormat:@"iOS%ld.gif",(long)@(NSDate.date.timeIntervalSince1970).integerValue];
    [upManager putData:data key:keyName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if ([resp.allKeys containsObject:@"key"]) {
            NSString * imageUrl = [NSString stringWithFormat:@"%@/%@",self.qnhead,resp[@"key"]];
            if (handle) {
                handle(imageUrl);
            }
        }
    } option:uploadOption];
    
}
//上传多张图片
- (void)uploadMoreImage:(NSArray<UIImage*>*)imageArray handle:(void (^)(BOOL, NSArray *))handle{
    NSMutableArray * imageurlArray = NSMutableArray.new;
    dispatch_group_t group = dispatch_group_create();
    for (UIImage * image in imageArray) {
        dispatch_group_enter(group);
        [self sendQiNiuWithImage:image handle:^(NSString * _Nonnull url) {
            if (url.length) {
                [imageurlArray addObject:url];
            }
            dispatch_group_leave(group);
        }];
        
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (handle) {
            if (imageArray.count == imageurlArray.count) {
                handle(YES,imageurlArray);
            }else{
                handle(NO,nil);
            }
            
        }
    });
}
#pragma mark --Private Method
- (NSString *)getImagePath:(UIImage *)image {
    NSString *filePath = nil;
    NSData *data = nil;
    if (UIImagePNGRepresentation(image) == nil) {
        data = UIImageJPEGRepresentation(image, 0.5);
    } else {
        data = UIImagePNGRepresentation(image);
    }
    
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSInteger num = arc4random()%10000000 + 300 + NSDate.date.timeIntervalSince1970;
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *ImagePath = [NSString stringWithFormat:@"/qn_upload_image_%ld.jpg",num];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
}
- (NSString *)getgifImagePath:(UIImage *)image {
    NSString *filePath = nil;
    NSData *data = nil;
    if (UIImagePNGRepresentation(image) == nil) {
        data = UIImageJPEGRepresentation(image, 0.5);
    } else {
        data = UIImagePNGRepresentation(image);
    }
    
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSInteger num = arc4random()%10000000 + 300;
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *ImagePath = [NSString stringWithFormat:@"/theFirstImage%ld.gif",num];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
}
- (void)sendDefultVideoWithPath:(NSString *)videoPath image:(UIImage *)image handle:(void (^)(BOOL, NSString *, NSString *))handle{
    dispatch_group_t group = dispatch_group_create();
    __block NSString * net_video_url;
    __block NSString * net_image_url;
    
    dispatch_group_enter(group);
    [self sendFileWithFilePath:videoPath type:@".mp4" handle:^(NSString *url) {
        dispatch_group_leave(group);
        net_video_url = url;
    }];
    dispatch_group_enter(group);
    [self sendQiNiuWithImage:image handle:^(NSString *url) {
        dispatch_group_leave(group);
        net_image_url = url;
    }];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (net_image_url.length && net_video_url.length) {
            if (handle) {
                handle(YES,net_video_url,net_image_url);
            }
        }else{
            if (handle) {
                handle(NO,net_video_url,net_image_url);
            }
        }
    });
}
@end
